package org.gc.util.dozer;

import java.util.ArrayList;
import java.util.List;

import net.sf.dozer.util.mapping.DozerBeanMapper;

import org.gc.webapp.util.page.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;



@Component
public class DozerBeanUtil {

    @Autowired
    private DozerBeanMapper dozerBeanMapper;


    @SuppressWarnings("unchecked")
    public <P> P clone(P base) {
        if (base == null) {
            return null;
        } else {
            return (P) dozerBeanMapper.map(base, base.getClass());
        }

    }

    public <P> List<P> cloneList(List<P> baseList) {

        if (baseList == null) {
            return null;
        } else {
            List<P> targetList = new ArrayList<P>();
            for (P p : baseList) {

                targetList.add((P) clone(p));
            }
            return targetList;
        }

    }

    @SuppressWarnings("unchecked")
    public <V, P> P convert(V base, P target) {

        if (base != null) {
            dozerBeanMapper.map(base, target);
            return target;
        }
        return target;
    }

    @SuppressWarnings("unchecked")
    public <V, P> P convert(V base, Class<P> target) {
        if (base == null) {
            return null;
        } else {
            P p = (P) dozerBeanMapper.map(base, target);
            return p;
        }

    }

    public <V, P> List<P> convertList(List<V> baseList, Class<P> target) {

        if (baseList == null) {
            return null;
        } else {
            List<P> targetList = new ArrayList<P>();
            for (V vo : baseList) {

                targetList.add((P) convert(vo, target));
            }
            return targetList;
        }

    }
    @SuppressWarnings("unchecked")
    public <V, P> PageList<P> convertPageList(PageList<V> basePageList, Class<P> target){
        if (basePageList == null) {
            return null;
        } else {
            List<P> targetList = new ArrayList<P>();
            List<V> baseList = basePageList.getList();
            for (V vo : baseList) {

                targetList.add((P) convert(vo, target));
            }
            PageList<P> result = new PageList<P>();
            result = convert(basePageList, result.getClass());
            result.setList(targetList);
            return result;
        }
    }
}
